package com.example.demoexample.camera;
import android.util.Log;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ServerListeningThread extends Thread {

    public ServerListeningThread(){
        new ServerListeningThread(8000).start();
    }

//    public static void main(String[] args) {
//        new ServerListeningThread(8080).start();
//    }

    private int bindPort;
    private ServerSocket serverSocket;
    private static final String TAG = "ServerListeningThread";
    public ServerListeningThread(int port) {
        this.bindPort = port;
    }

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(bindPort);
            while (true) {
                Socket rcvSocket = serverSocket.accept();
                // 获取手机连接的地址及端口号
                final String address = rcvSocket.getRemoteSocketAddress().toString();
                Log.e(TAG,"连接成功，连接的设备为：" + address);

                //单独写一个类，处理接收的Socket，类的定义在下面
                HttpRequestHandler request = new HttpRequestHandler(rcvSocket);
                request.handle();

                rcvSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //最后要确保以下把ServerSocket关闭掉
            if (serverSocket != null && !serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class HttpRequestHandler {
    private Socket socket;

    public HttpRequestHandler(Socket socket) {
        this.socket = socket;
    }

    public void handle() throws IOException {
        StringBuilder builder = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(socket.getInputStream());
        char[] charBuf = new char[1024];
        int mark = -1;
        while ((mark = isr.read(charBuf)) != -1) {
            builder.append(charBuf, 0, mark);
            if (mark < charBuf.length) {
                break;
            }
        }
        if (mark == -1) {
            return;
        }

        Map<String, String> headers = new HashMap<>();
        Map<String, String> parameters = new HashMap<>();

        String[] splits = builder.toString().split("\r\n");
        int index = 1;

        //处理header
        while (splits[index].length() > 0) {
            String[] keyVal = splits[index].split(":");
            headers.put(keyVal[0], keyVal[1].trim());
            index++;
        }
        String body = splits[index + 1];
        String[] bodySplits = body.split("&");

        //处理body的参数
        for (String str : bodySplits) {
            String[] param = str.split("=");
//            parameters.put(param[0], param[1]);
        }
        System.out.println(bodySplits);
        Log.e("ServerListeningThread","bodySplits = "+bodySplits);
        String respStr = "头部信息\r\n";
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            respStr += "名称: " + entry.getKey() + ", 值: " + entry.getValue() + "<br/>";

        }
        Log.e("ServerListeningThread","respStr = "+respStr);
//        respStr += "\r\nbody信息\r\n";
//        for (Map.Entry<String, String> entry : parameters.entrySet()) {
//            respStr += "名称: " + entry.getKey() + ", 值: " + entry.getValue() + "<br/>";
//        }

//        socket.getOutputStream().
//                write(("HTTP/1.1 200 OK\r\n" +
//                        "Content-Type: text/html; charset=utf-8\r\n" +
//                        "\r\n" +
//                        "<h1>这是响应报文</h1>\r\n" + respStr).getBytes("UTF-8"));
    }
}